package mu.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname LeetCode_01
 * @Description 两数之和
 *              给出一个数组和一个数，求数组中相加对于该数的两个元素的下标
 * @Date 2023/1/28 16:49
 * @Created by JiangMuyun
 */
public class LeetCode_01 {
    /*穷举，通俗易懂最垃圾写法*/
    public static int[] towindex(int[] nums, int target){
        if (nums.length < 2){
            System.out.println("数组长度不合法！");
            return null;
        }
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if (nums[i]+nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }

    /*进阶写法*/
    public static int[] towindex_plus(int[] nums, int target){
        /*key为元素值，value为元素对应的下标*/
        Map<Integer,Integer> map = new HashMap<>();
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int difference = target-nums[i];
            Integer differenceIndex = map.get(difference);
            if (differenceIndex != null){
                result[0] = i;
                result[1] = differenceIndex;
                break;
            }else {
                map.put(nums[i],i);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        /*
        * 穷举测试
        * */
        //int[] nums = {2,7,11,15};
        /*注：数组不能直接打印，要不然得到的是哈希值*/
        //System.out.println(Arrays.toString(towindex(nums, 9)));
//        int[] nums = {2,11,15,7};
//        System.out.println(Arrays.toString(towindex(nums, 9)));
        /*
        * 进阶测试
        * */
        int[] nums = { 3, 2, 4};
        System.out.println(Arrays.toString(towindex_plus(nums, 6)));
    }
}
